if (typeof Promise === 'undefined') {
    Promise = require("./es6-promise.min.js").Promise;
}

class Address {
    constructor() {
        this.app = getApp();
    }
    getList(cb) {
        return new Promise((resolve, reject) => {
            var list = this.app.address.list;
            if (list.length == 0 || this.app.address.hasChange) {
                this.app.http.get(this.app.config.address.list_url).then(res => {
                    this.app.address.list = res.data;
                    this.app.address.hasChange = false;
                    typeof cb === 'function' && cb(res.data);
                    resolve();
                }).catch(err => {
                    reject(err);
                })
            } else {
                typeof cb === 'function' && cb(list);
                resolve();
            }
        });
    }


    getSelected() {
        if (this.app.address.list.length == 0) {
            return;
        }
        var sel = null;
        var def = {};
        for (var i = 0; i < this.app.address.list.length; i++) {
            if (this.app.address.list[i].id == this.app.address.selected) {
                this.index = i;
                sel = this.app.address.list[i];
            }
            if (this.app.address.list[i].default) {
                def = { data: this.app.address.list[i], index: i };
            }
        }

        if (!sel && def) {
            sel = def.data;
            this.index = def.index;
        }
        if (!sel) {
            sel = this.app.address.list[0];
            this.index = 0;
        }


        return sel;
    }
}

module.exports = Address;